/*
 * Copyright 2016 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rhythms.swiperecyclerview;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rhythms.R;
import com.rhythms.swiperecyclerview.adapter.RhythmsAdapterMainList;
import com.rhythms.swiperecyclerview.bean.RhythmsItemBean;
import com.rhythms.swiperecyclerview.listener.OnItemClickListener;
import com.rhythms.swiperecyclerview.listener.OnItemPlayListener;
import com.rhythms.swiperecyclerview.utils.RhythmsSpUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Yan Zhenjie on 2016/8/3.
 */
public class RhythmsActMainList extends AppCompatActivity {

    @BindView(R.id.recycler_view)
    RecyclerView swipeMenuRecyclerView;
    private Activity mContext;

    private List<RhythmsItemBean> mRhythmsItemBeanList;

    private RhythmsAdapterMainList mRhythmsAdapterMainList;

    private Unbinder unbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rhythms_main_act);
        unbinder = ButterKnife.bind(this);
        ButterKnife.bind(this);
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mContext = this;

        String data = RhythmsSpUtil.getData(mContext);
        if("".equals(data)){
            mRhythmsItemBeanList = new ArrayList<>();
        } else {
            Gson gson = new Gson();
            Type type = new TypeToken<List<RhythmsItemBean>>() {
            }.getType();
            mRhythmsItemBeanList = gson.fromJson(data, type);
        }

        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
        swipeMenuRecyclerView.setLayoutManager(mLinearLayoutManager);// 布局管理器。
        swipeMenuRecyclerView.setHasFixedSize(true);// 如果Item够简单，高度是确定的，打开FixSize将提高性能。
        swipeMenuRecyclerView.setItemAnimator(new DefaultItemAnimator());// 设置Item默认动画，加也行，不加也行。

        mRhythmsAdapterMainList = new RhythmsAdapterMainList(mRhythmsItemBeanList);
        mRhythmsAdapterMainList.setOnItemClickListener(onItemClickListener);
        swipeMenuRecyclerView.setAdapter(mRhythmsAdapterMainList);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除绑定
        unbinder.unbind();
    }

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(int position, View view) {
//            Toast.makeText(mContext, "is" + position + "item", Toast.LENGTH_SHORT).show();
            switch (view.getId()) {
                case R.id.rhythms_id_delete:
//                    mRhythmsItemBeanList.remove(position);
//                    mRhythmsAdapterMainList.notifyDataSetChanged();
                    sureToDelete(position);
                    break;
                case R.id.rhythms_id_play:
                    // 开始
//                    RhythmsPlaySound.getInstance().startOneCycles(position, mRhythmsItemBeanList, onItemPlayListener);
                    break;
                case R.id.rhythms_id_main_item:
                    // edit
                    Intent intentEdit = new Intent(mContext, RhythmsActEdit.class);
                    Bundle bundle = new Bundle();
                    Gson gson = new Gson();
                    String itemDataStr = gson.toJson(mRhythmsItemBeanList.get(position));
                    bundle.putString("itemDataStr", itemDataStr);
                    bundle.putInt("position", position);
                    intentEdit.putExtras(bundle);
                    mContext.startActivityForResult(intentEdit, position);
                    break;

            }
        }
    };

    private void sureToDelete(final int position){
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("delete")
                .setMessage("sure to del")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mRhythmsItemBeanList.remove(position);
                        mRhythmsAdapterMainList.notifyDataSetChanged();
                    }
                })
                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).create();
        alertDialog.show();
    }

    private OnItemPlayListener onItemPlayListener = new OnItemPlayListener() {
        @Override
        public void onItemPlay(int position) {
            for (int i = 0; i < mRhythmsItemBeanList.size(); i++) {
                if(position == i){
                    mRhythmsItemBeanList.get(position).setRhyPlaying(true);
                } else {
                    mRhythmsItemBeanList.get(position).setRhyPlaying(false);
                }
            }
            mRhythmsAdapterMainList.notifyDataSetChanged();
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return true;
    }

    @OnClick({R.id.rhythms_id_add, R.id.rhythms_id_main_play, R.id.rhythms_id_main_sound, R.id.rhythms_id_main_stop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rhythms_id_add:
//                mRhythmsItemBeanList.add(new RhythmsItemBean());
//                mRhythmsAdapterMainList.notifyDataSetChanged();
                Intent intentEdit = new Intent(mContext, RhythmsActEdit.class);
//                mContext.startActivity(intentEdit);
                mContext.startActivityForResult(intentEdit, 1000);
                break;
            case R.id.rhythms_id_main_play:
                RhythmsPlaySound.getInstance().startOneCycles(0, mRhythmsItemBeanList, onItemPlayListener);
                break;
            case R.id.rhythms_id_main_stop:
                RhythmsPlaySound.getInstance().stopOneCycles();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("ddkkkdddkk", "onActivityResult:== "+data);
        Log.i("ddkkkdddkk", "requestCode:== "+requestCode);
        Log.i("ddkkkdddkk", "resultCode:== "+resultCode);
        // 如果是从过关界面返回
        if (resultCode == 3 && data != null) {
            String itemJsonData = data.getStringExtra("RhythmsItemBean");
            Log.i("ddkkkdddkk", "itemJsonData:== "+itemJsonData);
            Gson gson = new Gson();
            Type type = new TypeToken<RhythmsItemBean>() {
            }.getType();
            RhythmsItemBean rhythmsItemBean = gson.fromJson(itemJsonData, type);
            if (rhythmsItemBean != null) {
                if(requestCode == 1000){
                    mRhythmsItemBeanList.add(rhythmsItemBean);
                } else {
                    mRhythmsItemBeanList.set(requestCode,rhythmsItemBean);
                }
                mRhythmsAdapterMainList.notifyDataSetChanged();
                String json = gson.toJson(mRhythmsItemBeanList);
                RhythmsSpUtil.saveData(json, mContext);
            }
        }
    }
}